<template>
  <div class="main" style="height: 500px">

    <el-table
      v-loading="loading"
      :data="workerList.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%"
      height="630">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form style="margin-left: 50px" inline class="demo-table-expand">
            <el-form-item label="用户名">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-user-solid"></i>
                  <span>用户名:</span>
                </span>
              </span>
              <span>{{ props.row.username }}</span>
            </el-form-item>
            <el-form-item label="昵称">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-user"></i>
                  <span>昵称:</span>
                </span>
              </span>
              <span>{{ props.row.nickname }}</span>
            </el-form-item>
            <el-form-item label="密码">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-lock"></i>
                  <span>密码:</span>
                </span>
              </span>
              <el-button type="text" @click="openUpdatePassword(props.row)">
                <i class="el-icon-edit"></i>编辑密码
              </el-button>
            </el-form-item>
            <el-form-item label="联系电话">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-mobile-phone"></i>
                  <span>联系电话:</span>
                </span>
              </span>
              <span>{{ props.row.phone }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-s-help"></i>
                  <span>性别:</span>
                </span>
              </span>
              <span>{{ props.row.gender }}</span>
            </el-form-item>
            <el-form-item label="入职部门">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-school"></i>
                  <span>入职部门:</span>
                </span>
              </span>
              <span>{{ props.row.department }}</span>
            </el-form-item>
            <el-form-item label="状态">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-view"></i>
                  <span>状态:</span>
                </span>
              </span>
              <span v-if="props.row.entry">在职
              <el-button @click="changeEntry(props.$index, props.row)" type="text">员工已离职？</el-button></span>
              <span style="color: #f56c6c" v-else>离职</span>
            </el-form-item>
            <el-form-item label="更新时间">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-time"></i>
                  <span>更新时间:</span>
                </span>
              </span>
              <span>{{ props.row.updateTime }}</span>
            </el-form-item>
            <el-form-item label="员工头像">
              <span slot="label">
                <span class="span-box">
                  <i class="el-icon-s-custom"></i>
                  <span>员工头像:</span>
                </span>
              </span>
              <a v-if="props.row.avatar" target="_blank" :href="props.row.avatar">
                <i class="el-icon-view"></i>查看
              </a>
              <span v-else>他还没有上传头像</span>
            </el-form-item>
            <el-form-item>
              <el-button :disabled="!props.row.entry"
                         @click="handleListRole(props.row)"
                         type="info"
                         size="small"
                         plain>查看权限
              </el-button>
              <el-button :disabled="!props.row.entry"
                         type="primary"
                         @click="handleAddRole(props.row)"
                         size="small"
                         plain>添加权限
              </el-button>
              <el-button :disabled="props.row.entry"
                         @click="handleDeleteWork(props.$index, props.row.id)"
                         size="small"
                         type="danger"
                         plain>删除员工
              </el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        label="员工 ID"
        width="350"
        prop="id">
      </el-table-column>
      <el-table-column
        label="用户名"
        width="130"
        prop="username">
      </el-table-column>
      <el-table-column
        label="所在部门"
        width="140">
        <template slot-scope="scope">
          <el-tag >{{ scope.row.department }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="联系电话"
        width="150"
        prop="phone">
      </el-table-column>
      <el-table-column
        width="200"
        sortable
        label="入职时间"
        prop="createTime">
      </el-table-column>
      <el-table-column width="230" align="right">
<!--        <template slot="header" slot-scope="scope">-->
<!--          <el-input-->
<!--            v-model="search"-->
<!--            size="mini"-->
<!--            placeholder="输入用户名进行搜索"/>-->
<!--        </template>-->
        <template slot="header" slot-scope="scope">
          <el-form>
            <el-input v-model="username"  size="mini" placeholder="请输入员工名进行搜索" style="width:160px;float: left;margin-left: -10px" />
            <el-button type="primary" size="mini" @click="searchByName">查询</el-button>
          </el-form>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align:center;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.params.page"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="this.params.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
    </div>

    <el-dialog title="员工权限" :visible.sync="roleDialogVisible">
      <el-table v-loading="loading" :data="roleList">
        <el-table-column property="value" label="权限" width="300"></el-table-column>
        <el-table-column property="createTime" label="创建时间" width="300"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-popconfirm
              @confirm="handleDeleteRole(scope.$index, scope.row.id)"
              :title="'确定删除权限 < ' + scope.row.value +' > 吗？'"
            >
              <el-button slot="reference" size="small" type="danger" icon="el-icon-delete" plain>删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog width="450px" title="新增权限" :visible.sync="dialogFormVisible" @close="handleClose">
      <el-form ref="form" :model="addRoleForm">
        <el-form-item label="权限列表" label-width="120px" prop="value">
          <el-select v-model="addRoleForm.value" placeholder="请选择新增的权限">
            <el-option v-for="(item, index) in systemRoles"
                       :key="index"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRole">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    CreateWorkerRole,
    DeleteRoleByWorkerId,
    DeleteWorker,
    FindAllWorker,
    FindWorkerRoles,
    ListSystemRoles,
    UpdateWorker
  } from "@/api/worker";
  import config from "@/config";

  export default {


    data() {
      return {
        loading: false,
        addRoleForm: {
          wid: '',
          value: '',
        },
        workerList: [],
        systemRoles: [],
        roleDialogVisible: false,
        roleList: [],
        dialogFormVisible: false,
        search: '',
        total: 0,
        params: {
          page: 1,
          limit: 10,
        },
        username: '',
      }
    },

    mounted() {
      // FindAllWorker().then(res => {
      //   this.workerList = res.data
      // })
      this.listWorkerByPage();
      ListSystemRoles().then(res => {
        this.systemRoles = res.data
      })
    },

    methods: {
      searchByName() {
        let params = {
          page: this.params.page,
          limit: this.params.limit,
          username: this.username
        };
        this.$axios({
          method: 'get',
          url: config.API_URL + "/worker/like",
          params: params,
          headers: {
            "Authorization": localStorage.getItem("token")
          },
        })
          .then((res) => {
            console.log(res.data.data)
            this.workerList = res.data.data.list;
            this.total = res.data.data.total;
          })
          .catch((error) => {
            let errMsg = error.response.data.msg;
            this.$message.error(errMsg)
          })
      },

      openUpdatePassword(worker) {
        this.$prompt('请输入新的密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          if (!value) {
            this.$message({
              message: '密码不能为空',
              type: 'danger',
            });
            return
          }
          if (value.length < 6) {
            this.$message({
              message: '请输入不少于6位的密码',
              type: 'danger',
            });
            return
          }
          worker.password = value
          UpdateWorker(worker).then(res => {
            this.$message({
              message: '用户<' + worker.username + '>密码修改成功!',
              type: 'success',
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
        });
      },

      changeEntry(index, worker) {
        this.$confirm('此操作将该员工状态永久修改为离职, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          worker.entry = false
          UpdateWorker(worker).then(res => {
            this.$message({
              type: 'success',
              message: '员工离职成功!'
            });
          })
        })
      },

      handleDeleteWork(index, id) {
        DeleteWorker(id).then(res => {
          this.workerList.splice(index, 1)
          this.$message({
            type: 'success',
            message: '员工信息删除成功!'
          });
        })
      },

      handleListRole(worker) {
        this.roleDialogVisible = true;
        this.loading = true;
        FindWorkerRoles(worker.id).then(res => {
          setTimeout(() => {
            this.roleList = res.data
            this.loading = false
          }, 100)
        })
      },

      handleDeleteRole(index, id) {
        DeleteRoleByWorkerId(id).then(res => {
          if (res.success === true) {
            this.roleList.splice(index, 1)
            this.$message({
              type: 'success',
              message: '员工权限删除成功!'
            });
          }
        })
      },

      handleAddRole(worker) {
        this.dialogFormVisible = true;
        this.addRoleForm.wid = worker.id;
      },

      submitAddRole() {
        CreateWorkerRole(this.addRoleForm).then(res => {
          if (res.success) {
            this.dialogFormVisible = false;
            this.addRoleForm.wid = '';
            this.addRoleForm.value = '';
            this.$message({
              type: 'success',
              message: '员工权限添加成功!'
            });
          }
        })
      },

      handleClose(){
        this.$refs.form.resetFields();
      },

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.params.limit = val;
        this.listWorkerByPage();
      },

      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.params.page = val;
        this.listWorkerByPage();
      },

      listWorkerByPage:function(){
        this.$axios({
          method: 'get',
          url: config.API_URL + "/worker/page?page=" + this.params.page + "&limit=" + this.params.limit,
          headers: {
            "Authorization": localStorage.getItem("token")
          },
        })
          .then((res) => {
            console.log(res.data);
            this.workerList = res.data.data.list;
            this.total = res.data.data.total;
          });
      },

    }

  }
</script>

<style scoped>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
